//
//  GameListViewController.m
//  YoucApp
//
//  Created by Liam on 11/12/12.
//
//

#import "GameListViewController.h"

#import "YAObjGame.h"
#import "YAObjGameServer.h"

#import "GameCell.h"
#import "ServerCell.h"
#import "MoreGameCell.h"

#import "LoadMoreItem.h"

#import "WebViewController.h"

@interface GameListViewController ()

@property (retain, nonatomic) NSMutableDictionary *serverListDict;  // 游戏服务器列表
@property (retain, nonatomic) NSMutableDictionary *moreServerLoadingDict;   // 正在加载更多服务

- (BOOL)isMoreServerLoading:(NSString *)gameId;

- (void)setMoreServer:(NSString *)gameId loading:(BOOL)loading;

- (BOOL)isGameExpanded:(NSString *)gameId;

- (void)loadGameServer:(NSString *)gameId start:(NSInteger)start limit:(NSInteger)limit;

//- (BOOL)isGameServerLoading:(NSString *)gameId;

@end

@implementation GameListViewController

@synthesize serverListDict = _serverListDict;
@synthesize moreServerLoadingDict = _moreServerLoadingDict;

#pragma mark - local method

- (BOOL)isMoreServerLoading:(NSString *)gameId
{
    NSNumber *loading = [self.moreServerLoadingDict objectForKey:gameId];
    BOOL bRet = NO;
    
    if (loading)
    {
        bRet = [loading boolValue];
    }
    
    return bRet;
}

- (void)setMoreServer:(NSString *)gameId loading:(BOOL)loading
{
    NSNumber *number = [NSNumber numberWithBool:loading];
    [self.moreServerLoadingDict setObject:gameId forKey:number];
}

- (BOOL)isGameExpanded:(NSString *)gameId
{
    NSArray * serverList = [self.serverListDict objectForKey:gameId];
    return (serverList != nil);
}

//- (BOOL)isGameServerLoading:(NSString *)gameId
//{
//	NSArray * serverList = [self.serverListDict objectForKey:gameId];
//	return (serverList && serverList.count == 0);
//}

- (void)loadGameServer:(NSString *)gameId start:(NSInteger)start limit:(NSInteger)limit
{
    [self setMoreServer:gameId loading:YES];
    
    LMServerListParam *param = [[[LMServerListParam alloc] init] autorelease];
    param.gameId = gameId;
    param.start = start;
    param.limit = limit;
    param.context = self;
    
    [[ListManager instance] getGameServerList:param forceLoad:YES];
}

- (void)updateGameCell:(GameCell *)cell withItem:(YAObjGame *)item
{
    if (cell && item)
    {
        [cell setName:item.gameName];
        [cell setType:item.gameType];
        [cell setImageUrl:item.gameImage];
        [cell setExpand:[self isGameExpanded:item.gameId] animated:NO];
		[cell setGameId:item.gameId];
		[cell setIsAttention:item.isAttention];
		[cell setTodayNum:item.gameTodayNum];
    }
}

- (void)updateServerCell:(ServerCell *)cell withItem:(YAObjGameServer *)item
{
    if (cell && item)
    {
        cell.serverName.text = item.serverName;
        cell.platformName.text = item.platformName;
        cell.platformUrl.text = item.platformUrl;
        [cell setServerTimeInterval:item.serverTime];
    }
}

- (void)updateMoreServerCell:(MoreGameCell *)cell withItem:(LoadMoreServerItem *)item
{
    if (cell && item)
        [cell setLoading:item.isLoading];
}

- (void)updateLoadingServerCell:(MoreGameCell *)cell withItem:(LoadingServerItem *)item
{
    if (cell && item)
	{
        [cell setLoading:item.isLoading];
		[cell setNoMore:YES];
	}
}

- (void)didSelectGameCell:(GameCell *)cell withItem:(YAObjGame *)item
{
    BOOL bExpanded = [self isGameExpanded:item.gameId];
    
    [cell setExpand:!bExpanded animated:YES];
    if (bExpanded)
    {
        [self.serverListDict removeObjectForKey:item.gameId];
        [self constructCurrentShowList];
    }
    else
    {
        [self.serverListDict setObject:[NSMutableArray array] forKey:item.gameId];
        [self loadGameServer:item.gameId start:0 limit:5];
		[self constructCurrentShowList];
    }
}

- (void)didSelectServerCell:(ServerCell *)cell withItem:(YAObjGameServer *)item
{
    if (cell && item)
    {
        WebViewController *webViewController = [[[WebViewController alloc] init] autorelease];
		[webViewController loadURLString:item.gameUrl];
		[self.navigationController pushViewController:webViewController animated:YES];
    }
}

- (void)didSelectMoreServerCell:(MoreGameCell *)cell withItem:(LoadMoreServerItem *)item
{
    if (!item.isLoading)
    {
        item.isLoading = YES;
        
        // 加载更多服务
        int start = 0;
        NSArray * serverList = [self.serverListDict objectForKey:item.gameId];
        if (serverList)
            start = [serverList count];
        
        [self loadGameServer:item.gameId start:start limit:5];
        
        // 更新更多cell
        [self updateMoreServerCell:cell withItem:item];
    }
}

- (void)getServerListDidFinished:(NSArray *)list listParam:(LMServerListParam *)listParam error:(NSError *)error
{
	NSMutableArray * serverList = [self.serverListDict objectForKey:listParam.gameId];
	
	if ([serverList count] > 1)
	{
		// 删除更多按钮
		[serverList removeLastObject];
	}
	
    if ([error code] == YoucApiErrorSuccess)
    {
        if (list && serverList)
        {
            [serverList addObjectsFromArray:list];
        }
    }
	
	[self setMoreServer:listParam.gameId loading:NO];
	
	// 增加更多按钮
	LoadMoreServerItem *moreServerItem = [[[LoadMoreServerItem alloc] init] autorelease];
	moreServerItem.isLoading = [self isMoreServerLoading:listParam.gameId];
	moreServerItem.gameId = listParam.gameId;
	
	[serverList addObject:moreServerItem];
	
	[self constructCurrentShowList];
}

- (void)getGameServerListDidFinished:(NSNotification *)notification
{
    NSDictionary *dict = notification.userInfo;
    
    LMServerListParam *listParam = [dict objectForKey:LMListParamKey];
    if (listParam.context == self)
    {
        NSArray *list = [dict objectForKey:LMRESULT];
        NSError *error = [dict objectForKey:LMErrorKey];
        
        [self getServerListDidFinished:list listParam:listParam error:error];
    }
}

#pragma mark - defalut method
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.serverListDict = [NSMutableDictionary dictionary];
    self.moreServerLoadingDict = [NSMutableDictionary dictionary];
	
	[self createRefreshHeader];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getGameServerListDidFinished:) name:LMGetServerListDidFinishedNotification object:nil];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:LMGetServerListDidFinishedNotification object:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidUnload
{
    self.serverListDict = nil;
    self.moreServerLoadingDict = nil;
    [super viewDidUnload];
}

- (void)dealloc
{
    [_serverListDict release];
    [_moreServerLoadingDict release];
    [super dealloc];
}

#pragma mark - override method

//- (void)clearList
//{
//	self.gameList = nil;
//}

- (NSArray *)getShowList
{
    NSMutableArray *showList = [NSMutableArray arrayWithCapacity:[self.gameList count]];
    for (YAObjGame *game in self.gameList)
    {
        [showList addObject:game];
        NSArray * serverList = [self.serverListDict objectForKey:game.gameId];
        if (serverList)
        {
			if (serverList.count)
			{
	            [showList addObjectsFromArray:serverList];
			}
			else
			{
				LoadingServerItem *loadingServerItem = [[[LoadingServerItem alloc] init] autorelease];
				loadingServerItem.isLoading = YES;
				loadingServerItem.gameId = game.gameId;
				
				[showList addObject:loadingServerItem];
			}
        }
    }
    
    return showList;
}

- (void)getGameListDidFinished:(NSArray *)list error:(NSError *)error
{
    if ([error code] == YoucApiErrorSuccess)
    {
        NSMutableArray *array = [NSMutableArray arrayWithArray:self.gameList];
        [array addObjectsFromArray:list];
        
        self.gameList = array;
        
        if ([self.gameList count] == 0)
        {
            // TODO : 没有列表
        }
    }
	
	[self constructCurrentShowList];
}

- (NSArray *)getAssociateItems:(id)item
{
	NSMutableArray *items = [NSMutableArray array];
	
	YAObjGame *game = (YAObjGame *)item;
	if ([game isKindOfClass:[YAObjGame class]])
	{
		[items addObject:item];
		
		if ([self isGameExpanded:game.gameId])
		{
			NSArray * serverList = [self.serverListDict objectForKey:game.gameId];
			if (serverList)
			{
				[items addObjectsFromArray:serverList];
			}
		}
	}
	
	return items;
}

- (NSString *)getCellIdentifierByItem:(id)item
{
    NSString *identifier = nil;
    
    if ([item isKindOfClass:[YAObjGame class]])
    {
        identifier = @"GameCell";
    }
    else if ([item isKindOfClass:[YAObjGameServer class]])
    {
        identifier = @"ServerCell";
    }
    else if ([item isKindOfClass:[LoadMoreGameItem class]])
    {
        identifier = @"MoreGameCell";
    }
    else if ([item isKindOfClass:[LoadMoreServerItem class]])
    {
        identifier = @"MoreGameCell";
    }
	else if ([item isKindOfClass:[LoadingServerItem class]])
    {
        identifier = @"MoreGameCell";
    }
    
    return identifier;
}

- (void)updateCell:(UITableViewCell *)cell withItem:(id)item
{
    if ([item isKindOfClass:[YAObjGame class]])
    {
        [self updateGameCell:(GameCell *)cell withItem:item];
    }
    else if ([item isKindOfClass:[YAObjGameServer class]])
    {
        [self updateServerCell:(ServerCell *)cell withItem:item];
    }
    else if ([item isKindOfClass:[LoadMoreServerItem class]])
    {
        [self updateMoreServerCell:(MoreGameCell *)cell withItem:item];
    }
	else if ([item isKindOfClass:[LoadingServerItem class]])
	{
		[self updateLoadingServerCell:(MoreGameCell *)cell withItem:item];
	}
}

- (void)didSelectCell:(UITableViewCell *)cell withItem:(id)item
{
    if ([item isKindOfClass:[YAObjGame class]])
    {
        [self didSelectGameCell:(GameCell *)cell withItem:item];
    }
	else if ([item isKindOfClass:[YAObjGameServer class]])
    {
        [self didSelectServerCell:(ServerCell *)cell withItem:item];
    }
    else if ([item isKindOfClass:[LoadMoreServerItem class]])
    {
        [self didSelectMoreServerCell:(MoreGameCell *)cell withItem:item];
    }
}

@end
